<template>
    <div class="art-full-height">
        <ElCard class="art-table-card" shadow="never">

            <div class="content" v-loading="loading">
                <ElTabs v-model="activeTab" tab-position="left" class="config-tabs">
                    <ElTabPane label="基础信息" name="basic">
                        <ElForm :model="form" :rules="rules" ref="formRef" class="config-form">
                            <ElFormItem label="系统名称" prop="system_name">
                                <ElInput v-model="form.system_name" placeholder="请输入系统名称" />
                            </ElFormItem>
                            <ElFormItem label="默认语言" prop="language_default">
                                <ElSelect v-model="form.language_default" placeholder="请选择默认语言">
                                    <ElOption label="简体中文" value="zh-CN" />
                                    <ElOption label="English" value="en-US" />
                                </ElSelect>
                            </ElFormItem>
                            <ElFormItem label="时区" prop="timezone">
                                <ElInput v-model="form.timezone" placeholder="例如: Asia/Shanghai" />
                            </ElFormItem>
                        </ElForm>
                    </ElTabPane>

                    <ElTabPane label="邮件配置" name="email">
                        <ElForm :model="form" :rules="rules" class="config-form">
                            <ElFormItem label="邮件协议" prop="smtp_protocol">
                                <ElSelect v-model="form.smtp_protocol" placeholder="SMTP">
                                    <ElOption label="SMTP" value="SMTP" />
                                    <ElOption label="SMTP + SSL" value="SMTPS" />
                                </ElSelect>
                            </ElFormItem>
                            <ElFormItem label="服务器地址" prop="smtp_host">
                                <ElInput v-model="form.smtp_host" placeholder="请输邮箱服务器地址，如 smtp.qq.com" />
                            </ElFormItem>
                            <ElFormItem label="服务器端口" prop="smtp_port">
                                <ElInputNumber v-model="form.smtp_port" :min="1" :max="65535" />
                            </ElFormItem>
                            <ElFormItem label="邮箱账号" prop="smtp_user">
                                <ElInput v-model="form.smtp_user" placeholder="请输入发件邮箱账号" />
                            </ElFormItem>
                            <ElFormItem label="邮箱密码" prop="smtp_password">
                                <ElInput :type="showSmtpPassword ? 'text' : 'password'" v-model="form.smtp_password"
                                    placeholder="邮箱密码或授权码">
                                    <template #suffix>
                                        <ElIcon class="clickable" @click="showSmtpPassword = !showSmtpPassword">
                                            <View />
                                        </ElIcon>
                                    </template>
                                </ElInput>
                            </ElFormItem>
                            <ElFormItem label="SSL 加密" prop="smtp_ssl">
                                <ElRadioGroup v-model="form.smtp_ssl">
                                    <ElRadioButton :label="true">正常</ElRadioButton>
                                    <ElRadioButton :label="false">停用</ElRadioButton>
                                </ElRadioGroup>
                            </ElFormItem>
                            <ElFormItem label="状态" prop="smtp_enable">
                                <ElRadioGroup v-model="form.smtp_enable">
                                    <ElRadioButton :label="true">正常</ElRadioButton>
                                    <ElRadioButton :label="false">停用</ElRadioButton>
                                </ElRadioGroup>
                            </ElFormItem>
                            <ElFormItem label="发件人名称" prop="smtp_from_name">
                                <ElInput v-model="form.smtp_from_name" placeholder="例如：系统通知" />
                            </ElFormItem>
                            <ElFormItem label="发件人邮箱" prop="smtp_from_mail">
                                <ElInput v-model="form.smtp_from_mail" placeholder="noreply@example.com" />
                            </ElFormItem>
                            <div class="form-actions">
                                <ElButton type="primary" :loading="saving" @click="handleSave" v-ripple>修改</ElButton>
                            </div>
                        </ElForm>
                    </ElTabPane>

                    <ElTabPane label="登录配置" name="login">
                        <ElForm :model="form" :rules="rules" class="config-form">
                            <ElFormItem label="登录失败上限" prop="login_retry_limit">
                                <ElInputNumber v-model="form.login_retry_limit" :min="0" />
                            </ElFormItem>
                            <ElFormItem label="锁定时长(分钟)" prop="login_lock_minutes">
                                <ElInputNumber v-model="form.login_lock_minutes" :min="0" />
                            </ElFormItem>
                            <ElFormItem label="启用验证码" prop="captcha_required">
                                <ElSwitch v-model="form.captcha_required" />
                            </ElFormItem>
                            <ElFormItem label="多设备同时登录" prop="multi_device_login">
                                <ElSwitch v-model="form.multi_device_login" />
                            </ElFormItem>
                            <ElFormItem label="记住我天数" prop="remember_me_days">
                                <ElInputNumber v-model="form.remember_me_days" :min="0" />
                            </ElFormItem>
                        </ElForm>
                    </ElTabPane>

                    <ElTabPane label="安全配置" name="security">
                        <ElForm :model="form" :rules="rules" class="config-form">
                            <ElFormItem label="密码最小长度" prop="password_min_length">
                                <ElInputNumber v-model="form.password_min_length" :min="6" />
                            </ElFormItem>
                            <ElFormItem label="需包含大写字母" prop="password_require_upper">
                                <ElSwitch v-model="form.password_require_upper" />
                            </ElFormItem>
                            <ElFormItem label="需包含小写字母" prop="password_require_lower">
                                <ElSwitch v-model="form.password_require_lower" />
                            </ElFormItem>
                            <ElFormItem label="需包含数字" prop="password_require_number">
                                <ElSwitch v-model="form.password_require_number" />
                            </ElFormItem>
                            <ElFormItem label="需包含符号" prop="password_require_symbol">
                                <ElSwitch v-model="form.password_require_symbol" />
                            </ElFormItem>
                            <ElFormItem label="JWT Secret" prop="jwt_secret">
                                <ElInput v-model="form.jwt_secret" placeholder="用于签名的密钥" />
                            </ElFormItem>
                            <ElFormItem label="JWT 过期(分钟)" prop="jwt_expire_minutes">
                                <ElInputNumber v-model="form.jwt_expire_minutes" :min="1" />
                            </ElFormItem>
                            <ElFormItem label="刷新Token过期(天)" prop="refresh_expire_days">
                                <ElInputNumber v-model="form.refresh_expire_days" :min="1" />
                            </ElFormItem>
                            <ElFormItem label="允许来源(逗号分隔)" prop="allow_origins">
                                <ElInput v-model="form.allow_origins" placeholder="https://a.com, https://b.com" />
                            </ElFormItem>
                            <ElFormItem label="每分钟限流" prop="rate_limit_per_min">
                                <ElInputNumber v-model="form.rate_limit_per_min" :min="0" />
                            </ElFormItem>
                        </ElForm>
                    </ElTabPane>

                    <ElTabPane label="会话/令牌" name="token">
                        <ElForm :model="form" :rules="rules" class="config-form">
                            <ElFormItem label="会话超时(分钟)" prop="session_timeout_minutes">
                                <ElInputNumber v-model="form.session_timeout_minutes" :min="1" />
                            </ElFormItem>
                            <ElFormItem label="令牌头名称" prop="token_header_name">
                                <ElInput v-model="form.token_header_name" placeholder="例如 Authorization" />
                            </ElFormItem>
                            <ElFormItem label="令牌签发者" prop="token_issuer">
                                <ElInput v-model="form.token_issuer" />
                            </ElFormItem>
                            <ElFormItem label="令牌受众" prop="token_audience">
                                <ElInput v-model="form.token_audience" />
                            </ElFormItem>
                            <ElFormItem label="签名算法" prop="token_algorithm">
                                <ElSelect v-model="form.token_algorithm" placeholder="请选择">
                                    <ElOption label="HS256" value="HS256" />
                                    <ElOption label="HS384" value="HS384" />
                                    <ElOption label="HS512" value="HS512" />
                                </ElSelect>
                            </ElFormItem>
                        </ElForm>
                    </ElTabPane>

                    <ElTabPane label="通知/消息" name="notify">
                        <ElForm :model="form" :rules="rules" class="config-form">
                            <ElFormItem label="启用邮件通知" prop="notify_email_enable">
                                <ElSwitch v-model="form.notify_email_enable" />
                            </ElFormItem>
                            <ElFormItem label="启用Webhook" prop="notify_webhook_enable">
                                <ElSwitch v-model="form.notify_webhook_enable" />
                            </ElFormItem>
                            <ElFormItem label="Webhook URL" prop="webhook_url">
                                <ElInput v-model="form.webhook_url" placeholder="https://hooks.example.com/..." />
                            </ElFormItem>
                        </ElForm>
                    </ElTabPane>

                    <ElTabPane label="文件/上传" name="upload">
                        <ElForm :model="form" :rules="rules" class="config-form">
                            <ElFormItem label="最大大小(MB)" prop="upload_max_size_mb">
                                <ElInputNumber v-model="form.upload_max_size_mb" :min="1" />
                            </ElFormItem>
                            <ElFormItem label="允许类型" prop="upload_allowed_types">
                                <ElInput v-model="form.upload_allowed_types" placeholder="jpg,png,pdf" />
                            </ElFormItem>
                            <ElFormItem label="存储后端" prop="upload_storage_backend">
                                <ElSelect v-model="form.upload_storage_backend" placeholder="请选择">
                                    <ElOption label="Local" value="local" />
                                    <ElOption label="S3" value="s3" />
                                </ElSelect>
                            </ElFormItem>
                        </ElForm>
                    </ElTabPane>

                    <ElTabPane label="第三方集成" name="oauth">
                        <ElForm :model="form" :rules="rules" class="config-form">
                            <ElFormItem label="启用 OAuth 登录" prop="oauth_login_enable">
                                <ElSwitch v-model="form.oauth_login_enable" />
                            </ElFormItem>
                            <ElFormItem label="GitHub Client ID" prop="oauth_github_client_id">
                                <ElInput v-model="form.oauth_github_client_id" />
                            </ElFormItem>
                            <ElFormItem label="GitHub Client Secret" prop="oauth_github_client_secret">
                                <ElInput v-model="form.oauth_github_client_secret" type="password" />
                            </ElFormItem>
                            <ElFormItem label="Google Client ID" prop="oauth_google_client_id">
                                <ElInput v-model="form.oauth_google_client_id" />
                            </ElFormItem>
                            <ElFormItem label="Google Client Secret" prop="oauth_google_client_secret">
                                <ElInput v-model="form.oauth_google_client_secret" type="password" />
                            </ElFormItem>
                        </ElForm>
                    </ElTabPane>

                    <ElTabPane label="功能开关" name="feature">
                        <ElForm :model="form" :rules="rules" class="config-form">
                            <ElFormItem label="允许用户注册" prop="enable_registration">
                                <ElSwitch v-model="form.enable_registration" />
                            </ElFormItem>
                            <ElFormItem label="启用审计日志" prop="enable_audit_log">
                                <ElSwitch v-model="form.enable_audit_log" />
                            </ElFormItem>
                            <ElFormItem label="数据保留(天)" prop="data_retention_days">
                                <ElInputNumber v-model="form.data_retention_days" :min="0" />
                            </ElFormItem>
                        </ElForm>
                    </ElTabPane>
                </ElTabs>
            </div>
        </ElCard>
    </div>
</template>

<script setup lang="ts">
import { onMounted, ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { fetchSysConfig, updateSysConfig, type SysConfig } from '@/api/system/config'
import { View } from '@element-plus/icons-vue'

defineOptions({ name: 'SystemConfig' })

const activeTab = ref('basic')
const loading = ref(false)
const saving = ref(false)
const formRef = ref()
const showSmtpPassword = ref(false)

const form = reactive<SysConfig>({
    // 基础信息
    system_name: '',
    language_default: 'zh-CN',
    timezone: 'Asia/Shanghai',
    // 邮件
    smtp_enable: false,
    smtp_protocol: 'SMTP',
    smtp_host: '',
    smtp_port: 465,
    smtp_ssl: true,
    smtp_user: '',
    smtp_password: '',
    smtp_from_name: '',
    smtp_from_mail: '',
    // 登录
    login_retry_limit: 5,
    login_lock_minutes: 15,
    captcha_required: false,
    multi_device_login: false,
    remember_me_days: 7,
    // 安全
    password_min_length: 8,
    password_require_upper: true,
    password_require_lower: true,
    password_require_number: true,
    password_require_symbol: false,
    jwt_secret: '',
    jwt_expire_minutes: 60,
    refresh_expire_days: 7,
    allow_origins: '',
    rate_limit_per_min: 0,
    // 会话/令牌
    session_timeout_minutes: 30,
    token_header_name: 'Authorization',
    token_issuer: '',
    token_audience: '',
    token_algorithm: 'HS256',
    // 通知
    notify_email_enable: false,
    notify_webhook_enable: false,
    webhook_url: '',
    // 文件/上传
    upload_max_size_mb: 20,
    upload_allowed_types: 'jpg,png,pdf',
    upload_storage_backend: 'local',
    // 第三方集成
    oauth_login_enable: false,
    oauth_github_client_id: '',
    oauth_github_client_secret: '',
    oauth_google_client_id: '',
    oauth_google_client_secret: '',
    // 功能开关
    enable_registration: false,
    enable_audit_log: true,
    data_retention_days: 180
})

const rules = {
    system_name: [{ required: true, message: '请输入系统名称', trigger: 'blur' }],
    timezone: [{ required: true, message: '请输入时区', trigger: 'blur' }],
    smtp_host: [{ required: false, message: '请输入 SMTP 主机', trigger: 'blur' }],
    smtp_port: [{ type: 'number', required: false }],
    jwt_secret: [{ required: true, message: '请输入 JWT Secret', trigger: 'blur' }]
}

async function loadConfig() {
    loading.value = true
    try {
        const res = await fetchSysConfig()
        Object.assign(form, res || {})
    } catch (e) {
        // 后端未实现时，保持默认值
        console.warn('加载系统配置失败或未实现接口', e)
    } finally {
        loading.value = false
    }
}

async function handleSave() {
    if (!formRef.value) {
        saving.value = true
    }
    try {
        // 基本校验
        if (!form.system_name) {
            ElMessage.error('请填写系统名称')
            return
        }
        if (!form.jwt_secret) {
            ElMessage.error('请填写 JWT Secret')
            return
        }
        await updateSysConfig(form)
        ElMessage.success('保存成功')
    } catch (e) {
        console.error(e)
        ElMessage.error('保存失败')
    } finally {
        saving.value = false
    }
}

async function handleReset() {
    await loadConfig()
    ElMessage.success('已重置为服务器配置')
}

onMounted(loadConfig)
</script>

<style scoped>
.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.actions {
    display: flex;
    gap: 8px;
}

.content {
    padding: 8px 0;
}

.config-tabs :deep(.el-tabs__content) {
    padding-left: 24px;
}

.config-form {
    max-width: 640px;
}

.form-actions {
    margin-top: 12px;
}

.clickable {
    cursor: pointer;
}
</style>
